<?php

namespace App\Services\Gallery\Services;

use App\Exceptions\ServiceException;
use App\Services\Gallery\Interfaces\SpaceSchemeServiceInterface;
use App\Services\Gallery\Model\SpaceScheme;
use App\Services\Gallery\Model\SpaceSchemeContentCategory;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class SpaceSchemeService implements SpaceSchemeServiceInterface
{
    public function index($request)
    {
        $keywords = $request['keywords'] ?? '';
        $sort = $request['sort'] ?? 'sort';
        $order = $request['order'] ?? 'asc';
        $size = $request['size'] ?? 50;
        $is_recommend = $request['is_recommend'] ?? '';
        $minacreage = $request['minacreage'] ?? '';
        $maxacreage = $request['maxacreage'] ?? '';
        $data = SpaceScheme::query()
            ->when($keywords, function ($query) use ($keywords) {
                return $query->where('title', 'like', '%' . $keywords . '%');
            })
            ->when($is_recommend, function ($query) use ($is_recommend) {
                return $query->where('is_recommend', '=', $is_recommend);
            })
            ->when($minacreage && $maxacreage, function ($query) use ($minacreage, $maxacreage) {
                return $query->where('acreage', '>=', $minacreage)
                    ->where('acreage', '<=', $maxacreage);
            })
            ->orderBy("is_show", "desc")
            ->orderBy($sort, $order)
            ->orderBy("updated_at", "desc")
            ->paginate($size);

        $data->appends($request);

        return $data->toArray();
    }

    public function set($request, $id = 0)
    {
        if ($id) {
            $data = SpaceScheme::findOrFail($id);
        } else {
            $data = new SpaceScheme();
        }
        $data->user()->associate(Auth::id());
        $data->fill($request)->save();

        return $data->toArray();
    }

    public function get($id)
    {
        return SpaceScheme::query()->where('id', $id)->firstOrFail()->toArray();
    }

    public function destroy($id)
    {
        $data = SpaceScheme::findOrFail($id);
        $data->delete();
    }

    public function list()
    {
        $data = SpaceScheme::query()->show()->orderBy('sort','asc')->get();

        return $data->toArray();
    }
}
